/**
 * Created by webhugo on 16-10-18.
 */
const {Url} = require("url")
const format = require("url").format

const db = require('../../model/index')
const utilx = require('../../lib/utilx')
const responser = require('../../lib/responser')
const auth = require('../../helper/auth')
const Config = require('../../config/config')
const {Check, CheckNull} = require("../../lib/check")
const pkg = require("../../package.json")

const staticPrefix = Config.staticPrefix

const Model = db.models
const Course = Model.Course
const Rel = Model.Rel
const File = Model.File
const Comment = Model.Comment
const User = Model.User

function changeCourseStaticFilePath(course) {
    var URL = new Url()
    URL.protocol = staticPrefix.protocol
    URL.hostname = staticPrefix.hostname
    URL.port = staticPrefix.port

    var pattern = /http:\/\/[^/]*\//g;
    URL.pathname = course.cover.replace(pattern, '');
    course.cover = format(URL)

    URL.pathname = course.location.replace(pattern, '');
    course.location = format(URL)

    return course
}

function changeStaticFilePath(file) {
    var URL = new Url()
    URL.protocol = staticPrefix.protocol
    URL.hostname = staticPrefix.hostname
    URL.port = staticPrefix.port

    URL.pathname = file.location
    file.location = format(URL)

    return file
}

module.exports = router => {
    /**
     * 返回所有课程
     *
     //  hot 0代表不按热度,1表示按热度
     //  star 0表示不按评分高低,1表示按评分高低
     //  follow 0代表不按关注人数,1表示按关注人数
     // var hot = query.hot ? query.hot : 0;
     // var star = query.star ? query.star : 1;
     // var follow = query.follow ? query.follow : 1;
     */
    router.get("/course/all", async (ctx) => {

        var where = {}

        var query = ctx.request.query

        var major = query.major
        const majors = ["web", "android", "ios", "ui", "qianrushi"]
        const majorsInDb = ["Web", "Android", "IOS", "UI", "嵌入式"]
        if (major && majors.indexOf(major) !== -1) {
            where.major = majorsInDb[majors.indexOf(major)]
        }

        var st = query.st
        if (st) {
            where.$or = {
                title: {
                    $like: `%${st}%`
                },
                description: {
                    $like: `%${st}%`
                },
                teacher: {
                    $like: `%${st}%`
                }
            }
        }

        var courses = await Course.findAll({
            where
        }).map((course) => {
            return changeCourseStaticFilePath(course)
        })

        responser.success(ctx, courses)
    })

    router.get("/course/recommend", async (ctx) => {
        const majors = ["Web", "Android", "IOS", "UI", "嵌入式"]
        var coursesRecommend = []
        for (var m of majors) {
            var courses = await Course.findAll({
                where: {
                    major: m
                },
                limit: 8,
                order: [["createdAt", "DESC"]]
            }).map((course_temp) => {
                return changeCourseStaticFilePath(course_temp)
            })

            coursesRecommend.push(courses)
        }
        responser.success(ctx, coursesRecommend)
    })

    /**
     * limit 和 lastId 是返回的课程多少
     * level是按简单1,中级2,困难3
     */
    router.get('/course/list', async (ctx, next) => {
        // Check(ctx, ["limit", "toInt"])

        let conditions = {
            where: {}
        };

        let query = ctx.query;
        let page = query.page || 1;
        //todo: 课程难度 1简单 2普通 3困难
        conditions.where.difficulty = query.level || {$in: [1, 2, 3]};

        conditions.limit = query.limit || 10;


        conditions.offset = (page - 1) * conditions.limit;
        conditions.order = [["followNum", "DESC"], ["score", "DESC"]];
        //todo: 模糊查询
        if (query.search) {
            conditions.where.title = {
                like: `%${query.search}%`
            };
        }

        try {
            console.log(conditions);
            let courses = await Course.findAll(conditions)
                .map((course) => {
                    return changeCourseStaticFilePath(course)
                })

            responser.success(ctx, courses)
            return
        } catch (e) {
            console.trace(e);
            responser.catchErr(ctx, e);
            return;
        }
    });

    /**
     * id 是课程的id，返回具体课程
     */
    router.get('/course/specific/:id', async (ctx, next) => {
        var id = ctx.params.id;
        console.log(id);
        if (!id) {
            responser.catchErr(ctx, "id is null");
            return;
        }
        try {

            var course = await Course.findOne({
                where: {
                    id: id
                },
                include: [
                    {
                        model: Model.FieldsOfCourse,
                        include: [Model.Field]
                    },
                    {
                        model: Model.Chapter,
                        include: [Model.Lesson]
                    }
                ]
            }).then((c_temp) => {
                return changeCourseStaticFilePath(c_temp)
            })

        } catch (e) {
            responser.catchErr(ctx, e);
        }
        if (!course) {
            responser.catchErr(ctx, "do not have this course", 0);
            return;
        }
        if (!ctx.currentUser) {
            responser.success(ctx, {
                course: course,
                isLike: null,
                isFollow: null,
                tip: "user has not logined"
            });
            return;
        }
        else {
            var data = {
                course: course,
                isLike: (await Rel.count({
                    where: {
                        CourseId: id,
                        UserId: ctx.currentUser.id,
                        type: 1
                    }
                })) != 0,
                isFollow: (await Rel.count({
                    where: {
                        CourseId: id,
                        UserId: ctx.currentUser.id,
                        type: 2
                    }
                })) != 0
            };
            responser.success(ctx, data);
            return;
        }

    });


    /**
     * todo:课程喜欢,如果已经是喜欢则取消喜欢
     */
    router.post("/course/like/:id", async (ctx, next) => {
        var id = ctx.params.id;
        if (!id) {
            responser.catchErr(ctx, "id is null");
            return;
        }
        let rel = {
            CourseId: id,
            type: 1
        };
        let user = ctx.currentUser;
        user = user ? user : (await auth.user(ctx));
        if (user) {
            rel.UserId = user.id;
        }
        try {
            let count = await Rel.count({
                where: rel
            });
            console.log(count);
            if (count) {
                console.log(rel);
                await Rel.destroy({
                    where: rel
                });
            } else {
                await Rel.create(rel);
            }
        } catch (e) {
            responser.catchErr(ctx, e);
            return;
        }
        responser.success(ctx);
    });

    /**
     * todo:课程关注, 如果已经关注则取消
     */
    router.post("/course/follow/:id", async (ctx, next) => {
        var id = ctx.params.id;
        if (!id) {
            responser.catchErr(ctx, "id is null");
            return;
        }
        let rel = {
            CourseId: id,
            type: 2
        };
        let user = ctx.currentUser;
        user = user ? user : (await auth.user(ctx));
        if (user) {
            rel.UserId = user.id;
        }
        try {
            let count = await Rel.count({
                where: rel
            });
            console.log(count);
            if (count) {
                console.log(rel);
                await Rel.destroy({
                    where: rel
                });
            } else {
                await Rel.create(rel);
            }
        } catch (e) {
            responser.catchErr(ctx, e);
            return;
        }
        responser.success(ctx);
    });

    router.get('/course/video/:id', async (ctx, next) => {
        let id = ctx.params.id;
        if (!id) {
            responser.catchErr(ctx, "id is null");
            return;
        }
        //测试
        ctx.redirect(Config.videoUrl.url + "/default_video.mp4");
        // ctx.redirect(Config.videoUrl.url+"/web_1_video.mp4")
        // ctx.redirect(Config.videoUrl.url+"/ios_1_video.mp4")
    })

    router.post("/admin/course/info/edit", async (ctx, next) => {
        Check(ctx, "title", "description", "major", "location", "cover", ["id", "toInt"])

        var body = ctx.request.body

        await Course.update({
            title: body.title,
            description: body.description,
            major: body.major,
            location: body.location,
            cover: body.cover
        }, {
            where: {
                id: body.id
            }
        })

        var course = await Course.findOne({
            where: {
                id: body.id
            }
        }).then((c_temp) => {
            return changeCourseStaticFilePath(c_temp)
        })

        responser.success(ctx, course)
    })

    router.post("/admin/course/add", async (ctx) => {
        Check(ctx, "title", "description", "major", "location", "cover")

        var body = ctx.request.body

        var course = await Course.create({
            participantCount: 0,
            difficulty: 1,
            starNum: 1,
            followNum: 1,
            teacher: "BOSS",
            score: 0,
            chapter: 0,

            title: body.title,
            description: body.description,
            major: body.major,
            location: body.location,
            cover: body.cover
        }).then((c_temp) => {
            changeCourseStaticFilePath(c_temp)
        })

        responser.success(ctx, course)
    })

    router.post("/admin/course/del", async (ctx) => {
        Check(ctx, "id")

        var body = ctx.request.body
        var isDeleted = true

        try {
            await Course.destroy({
                where: {
                    id: body.id
                }
            })
        } catch (err) {
            isDeleted = false
        }

        isDeleted ? responser.success(ctx, isDeleted) : responser.reject(ctx, isDeleted)
    })

    router.get("/admin/course/files/all", async (ctx) => {
        Check(ctx, "courseId")

        var query = ctx.request.query
        var courseId = parseInt(query.courseId)

        var files = await File.findAll({
            where: {
                CourseId: courseId
            }
        }).map((file_temp) => {
            return changeStaticFilePath(file_temp)
        })

        responser.success(ctx, files)
    })

    router.post("/admin/course/files/add", async (ctx) => {
        Check(ctx, ["courseId", "toInt"], "title", "location")

        var body = ctx.request.body
        var courseId = body.courseId
        var title = body.title
        var location = body.location

        var file = await File.create({
            CourseId: courseId,
            title,
            location
        }).then((file_temp) => {
            return changeStaticFilePath(file_temp)
        })

        responser.success(ctx, file)
    })

    router.post("/admin/course/files/del", async (ctx) => {
        Check(ctx, "id")

        var body = ctx.request.body

        var isDeleted = true
        try {
            await File.destroy({
                where: {
                    id: body.id
                }
            })
        } catch (err) {
            isDeleted = false
        }

        isDeleted ? responser.success(ctx, isDeleted) : responser.reject(ctx, isDeleted)
    })

    router.get("/course/comments/all", async (ctx) => {
        Check(ctx, "isNote")

        var query = ctx.request.query
        var isNote = parseInt(query.isNote)
        var courseId = query.courseId
        var userId = query.userId

        var where = {
            isNote
        }
        if (userId) {
            where.UserId = userId
        }
        if (courseId) {
            where.CourseId = courseId
        }


        var comments = await Comment.findAll({
            where,
            include: [{
                model: User,
                attributes: {
                    exclude: ["password", "mobile", "email", "createdAt", "updatedAt", "type"]
                }
            }, {
                model: Course,
                attributes: ["major", "title", "id"]
            }],
            order: [["createdAt", "DESC"]]
        })

        responser.success(ctx, comments)
    })

    router.post("/admin/course/comments/del", async (ctx) => {
        Check(ctx, "id", ["isNote", "toInt"])

        var body = ctx.request.body
        var id = body.id
        var isNote = body.isNote

        var isDeleted = true
        try {
            await Comment.destroy({
                where: {
                    id,
                    isNote
                }
            })
        } catch (err) {
            isDeleted = false
        }

        isDeleted ? responser.success(ctx, isDeleted) : responser.reject(ctx, isDeleted)
    })
};